package com.nsharmon.webapp.listeners;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.jboss.logging.Logger;

public class HibernateSessionListener implements ServletContextListener {
	private static final String ATTR_SESSION_FACTORY = "HIBERNATE_SESSION_FACTORY";
	private Logger logger = Logger.getLogger(this.getClass());
	private static SessionFactory sessionFactory = null;
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		if(sessionFactory != null) {
			logger.info("Destroying SessionFactory.");
			sessionFactory.close();
			
			arg0.getServletContext().removeAttribute(ATTR_SESSION_FACTORY);
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		logger.info("Initializing SessionFactory.");
		
        // Create the SessionFactory from hibernate.cfg.xml				
		try {

			// Documentation is clear on this:
			// Should use below code because old way is deprecated.
			// However they are also "working on it" and hence isn't yet functional.
			
//			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().configure().buildServiceRegistry();
//			MetadataSources metadataSources = new MetadataSources(serviceRegistry);
//			metadataSources.addResource("hibernate.cfg.xml");
//	
//			sessionFactory = metadataSources.buildMetadata().buildSessionFactory();
			
			Configuration conf = new Configuration()
				.configure("hibernate.cfg.xml");
			sessionFactory = conf.buildSessionFactory();
			
			arg0.getServletContext().setAttribute(ATTR_SESSION_FACTORY, sessionFactory);
		} catch (Throwable ex) {
			logger.fatal("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }	
	}
	
	public static Session openSession() {
		return sessionFactory.openSession();
	}
}
